<template>
  <div class="file-upload"
       v-loading="loading"
       element-loading-text="loading..."
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(0, 0, 0, 0.8)">
    <el-upload
      class="upload-demo"
      ref="upload"
      action=""
      multiple
      :auto-upload="false"
      :fileList="fileList"
      :on-change="handleFjChange"
      :on-exceed="handleExceed"
      :show-file-list="false"
      v-bind="$props"
    >
      <slot>
        <el-button size="small" type="primary">选择文件</el-button>
      </slot>
    </el-upload>
    <upload-list :files="fileList" :list-type="listType" @remove="onRemove"/>
  </div>
</template>

<script>
import uploadList from './upload-list'
import dao from './uploadAction'
import {postSysFileDeleteId} from '$my/code/api/sys-file'

const MAX_SIZE = 1024 * 1024 * 500

export default {
  name: 'file-upload',
  cnName: 'file-upload',
  components: {
    uploadList
  },
  props: {
    accept: String,
    listType: String,
    params: Object,
    limit: Number
  },
  data() {
    return {
      loading: false,
      fileList: []
    }
  },
  methods: {
    handleFjBeforeUpload() {
      return false
    },
    handleExceed(files, fileList) {
      this.$notify.warning('上传文件不能超过上限:' + this.limit)
    },
    handleFjChange(file, fileList) {
      if(file.size >= MAX_SIZE) {
        this.$message.warning('上传文件请不要超过500MB!')
        return
      }

      const params = {
        ...this.params,
        file: file.raw
      }
      this.loading = true
      dao.upload(params, '/file/uploadFile').then(res => {
        this.loading = false
        this.fileList.push(res)

        this.$emit('upload-success')
      }).catch(e => {
        this.loading = false
      })
    },
    onRemove(file) {
      const {fileId} = file


      const index = this.fileList.findIndex(o => o.fileId === fileId)
      if(fileId) {
        this.loading = true
        postSysFileDeleteId(fileId).then(_ => {
          this.loading = false
          this.fileList.splice(index, 1)
        }).catch(e => {
          this.loading = false
        })
      } else {
        this.fileList.splice(index, 1)
      }

    },
    getData() {
      return this.fileList
    }
  }
}
</script>

<style lang="scss" scoped>
.file-upload {
}
</style>
